{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b4018c8b",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'pQLOHjaGDhbIjawrclfoL15l'\n",
    "SECRET_KEY = 'qtWaaNx5meIHk6gIy8uZ2NUL3MnFBjd6'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3472370a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.4e1ff0d3f1cfb76f7b570a2178182b70.315360000.1968149463.282335-25345318\",\"expires_in\":2592000,\"session_key\":\"9mzdDtR7Fp6IHXTj2oF3S0ZOI1toj7tftXBGr3eNP4Oztoj0kuffD6iXw1O2w1SiAKAEdNhflvlkCIE+vi\\/4V2YRlIg9cA==\",\"access_token\":\"24.5f5eff21d201acf9609e0b31a8b4ddf1.2592000.1655381463.282335-25345318\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"6163f180fc8c7ba702a434b6b49c596c\"}\n",
      "\n",
      "{'refresh_token': '25.4e1ff0d3f1cfb76f7b570a2178182b70.315360000.1968149463.282335-25345318', 'expires_in': 2592000, 'session_key': '9mzdDtR7Fp6IHXTj2oF3S0ZOI1toj7tftXBGr3eNP4Oztoj0kuffD6iXw1O2w1SiAKAEdNhflvlkCIE+vi/4V2YRlIg9cA==', 'access_token': '24.5f5eff21d201acf9609e0b31a8b4ddf1.2592000.1655381463.282335-25345318', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '6163f180fc8c7ba702a434b6b49c596c'}\n",
      "SUCCESS WITH TOKEN: 24.5f5eff21d201acf9609e0b31a8b4ddf1.2592000.1655381463.282335-25345318 ; EXPIRES IN SECONDS: 2592000\n",
      "url is http://vop.baidu.com/server_api?cuid=123456PYTHON&token=24.5f5eff21d201acf9609e0b31a8b4ddf1.2592000.1655381463.282335-25345318&dev_pid=1537\n",
      "header is {'Content-Type': 'audio/wav; rate=16000', 'Content-Length': 129998}\n",
      "Request time cost 0.405801\n",
      "{\"corpus_no\":\"7098676691587104174\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"80539173941652789463\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = 'audio/16k.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "def asr(token,AUDIO_FILE)\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "    print(\"url is\", url);\n",
    "    print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "        return result_str"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fcf0473",
   "metadata": {},
   "source": [
    "# 语音识别自动回复文本机器人\n",
    "\n",
    "> 1. 准备录制音频文件\n",
    "> 2. 调用语音识别，将音频转成文本（已完成）\n",
    "> 3. 文本自动回复（）原理：问和答"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0a0a6c38",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 3.1 准备录制文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "13bd9faf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: SpeechRecognition in d:\\pra\\anaconda3\\lib\\site-packages (3.8.1)\n"
     ]
    }
   ],
   "source": [
    "!pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c3d42c2e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pipwin\n",
      "  Downloading pipwin-0.5.2.tar.gz (7.9 kB)\n",
      "Collecting docopt\n",
      "  Downloading docopt-0.6.2.tar.gz (25 kB)\n",
      "Requirement already satisfied: requests in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Collecting pyprind\n",
      "  Downloading PyPrind-2.11.3-py2.py3-none-any.whl (8.4 kB)\n",
      "Requirement already satisfied: six in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Collecting js2py\n",
      "  Downloading Js2Py-0.71-py3-none-any.whl (1.0 MB)\n",
      "Requirement already satisfied: packaging in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (20.9)\n",
      "Collecting pySmartDL>=1.3.1\n",
      "  Downloading pySmartDL-1.3.4-py3-none-any.whl (20 kB)\n",
      "Requirement already satisfied: soupsieve>1.2 in d:\\pra\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Collecting tzlocal>=1.2\n",
      "  Downloading tzlocal-4.2-py3-none-any.whl (19 kB)\n",
      "Collecting pyjsparser>=2.5.1\n",
      "  Downloading pyjsparser-2.7.1.tar.gz (24 kB)\n",
      "Collecting pytz-deprecation-shim\n",
      "  Downloading pytz_deprecation_shim-0.1.0.post0-py2.py3-none-any.whl (15 kB)\n",
      "Collecting backports.zoneinfo\n",
      "  Downloading backports.zoneinfo-0.2.1-cp38-cp38-win_amd64.whl (38 kB)\n",
      "Collecting tzdata\n",
      "  Downloading tzdata-2022.1-py2.py3-none-any.whl (339 kB)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in d:\\pra\\anaconda3\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: idna<3,>=2.5 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (2020.12.5)\n",
      "Building wheels for collected packages: pipwin, docopt, pyjsparser\n",
      "  Building wheel for pipwin (setup.py): started\n",
      "  Building wheel for pipwin (setup.py): finished with status 'done'\n",
      "  Created wheel for pipwin: filename=pipwin-0.5.2-py2.py3-none-any.whl size=8776 sha256=2aa2e8a1dd8395d1c7bd155e483d2a390a78eb805e40903d882ba91bd66e6a41\n",
      "  Stored in directory: c:\\users\\xxxibgdrgn\\appdata\\local\\pip\\cache\\wheels\\f4\\a8\\76\\372879a40d2d4dd7de23efd867ed37112687429b8d0dda4545\n",
      "  Building wheel for docopt (setup.py): started\n",
      "  Building wheel for docopt (setup.py): finished with status 'done'\n",
      "  Created wheel for docopt: filename=docopt-0.6.2-py2.py3-none-any.whl size=13705 sha256=f0473a05373dd4975cd1bf303c4b85f2f9922bf800ea9fa6c7c060c1eaf1b246\n",
      "  Stored in directory: c:\\users\\xxxibgdrgn\\appdata\\local\\pip\\cache\\wheels\\56\\ea\\58\\ead137b087d9e326852a851351d1debf4ada529b6ac0ec4e8c\n",
      "  Building wheel for pyjsparser (setup.py): started\n",
      "  Building wheel for pyjsparser (setup.py): finished with status 'done'\n",
      "  Created wheel for pyjsparser: filename=pyjsparser-2.7.1-py3-none-any.whl size=25998 sha256=7eabe4ebdd79d4d42feb62ce2c0929e3d287b7eb5016ff1fa31e5b70e58cbafa\n",
      "  Stored in directory: c:\\users\\xxxibgdrgn\\appdata\\local\\pip\\cache\\wheels\\d5\\88\\34\\ccb5bb40eb3178a134eb293e6c363928c5bcfba0b91031db76\n",
      "Successfully built pipwin docopt pyjsparser\n",
      "Installing collected packages: tzdata, backports.zoneinfo, pytz-deprecation-shim, tzlocal, pyjsparser, pySmartDL, pyprind, js2py, docopt, pipwin\n",
      "Successfully installed backports.zoneinfo-0.2.1 docopt-0.6.2 js2py-0.71 pipwin-0.5.2 pySmartDL-1.3.4 pyjsparser-2.7.1 pyprind-2.11.3 pytz-deprecation-shim-0.1.0.post0 tzdata-2022.1 tzlocal-4.2\n",
      "Collecting pipwin\n",
      "  Using cached pipwin-0.5.2-py2.py3-none-any.whl\n",
      "Requirement already satisfied: packaging in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (20.9)\n",
      "Requirement already satisfied: pySmartDL>=1.3.1 in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (1.3.4)\n",
      "Collecting docopt\n",
      "  Using cached docopt-0.6.2-py2.py3-none-any.whl\n",
      "Requirement already satisfied: pyprind in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (2.11.3)\n",
      "Requirement already satisfied: requests in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Requirement already satisfied: six in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Requirement already satisfied: js2py in d:\\pra\\anaconda3\\lib\\site-packages (from pipwin) (0.71)\n",
      "Requirement already satisfied: soupsieve>1.2 in d:\\pra\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Requirement already satisfied: tzlocal>=1.2 in d:\\pra\\anaconda3\\lib\\site-packages (from js2py->pipwin) (4.2)\n",
      "Requirement already satisfied: pyjsparser>=2.5.1 in d:\\pra\\anaconda3\\lib\\site-packages (from js2py->pipwin) (2.7.1)\n",
      "Requirement already satisfied: pytz-deprecation-shim in d:\\pra\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.1.0.post0)\n",
      "Requirement already satisfied: backports.zoneinfo in d:\\pra\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.2.1)\n",
      "Requirement already satisfied: tzdata in d:\\pra\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (2022.1)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in d:\\pra\\anaconda3\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: idna<3,>=2.5 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\pra\\anaconda3\\lib\\site-packages (from requests->pipwin) (2020.12.5)\n",
      "Installing collected packages: docopt, pipwin\n",
      "Successfully installed docopt-0.6.2 pipwin-0.5.2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Usage:\n",
      "  pipwin install (<package> | [-r=<file> | --file=<file>]) [--proxy=<proxy>]\n",
      "  pipwin uninstall <package>\n",
      "  pipwin download (<package> | [-r=<file> | --file=<file>]) [-d=<dest> | --dest=<dest>] [--proxy=<proxy>]\n",
      "  pipwin search <package> [--proxy=<proxy>]\n",
      "  pipwin list\n",
      "  pipwin refresh [--log=<log>] [--proxy=<proxy>]\n",
      "  pipwin (-h | --help)\n",
      "  pipwin (-v | --version)\n"
     ]
    }
   ],
   "source": [
    "!pip install pipwin\n",
    "!pipwin instll PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7282d966",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "acc8c328",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "Could not find PyAudio; check installation",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32mD:\\pra\\Anaconda3\\lib\\site-packages\\speech_recognition\\__init__.py\u001b[0m in \u001b[0;36mget_pyaudio\u001b[1;34m()\u001b[0m\n\u001b[0;32m    107\u001b[0m         \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 108\u001b[1;33m             \u001b[1;32mimport\u001b[0m \u001b[0mpyaudio\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    109\u001b[0m         \u001b[1;32mexcept\u001b[0m \u001b[0mImportError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'pyaudio'",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-3-3a6eeaf0a773>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mspeech_recognition\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mRecognizer\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mspeech_recognition\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mMicrophone\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0msource\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      6\u001b[0m     \u001b[0maudio\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mr\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlisten\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0msource\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      7\u001b[0m \u001b[1;31m# 将数据保存到wav文件中\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\pra\\Anaconda3\\lib\\site-packages\\speech_recognition\\__init__.py\u001b[0m in \u001b[0;36m__init__\u001b[1;34m(self, device_index, sample_rate, chunk_size)\u001b[0m\n\u001b[0;32m     77\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     78\u001b[0m         \u001b[1;31m# set up PyAudio\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 79\u001b[1;33m         \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpyaudio_module\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_pyaudio\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     80\u001b[0m         \u001b[0maudio\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpyaudio_module\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mPyAudio\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     81\u001b[0m         \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\pra\\Anaconda3\\lib\\site-packages\\speech_recognition\\__init__.py\u001b[0m in \u001b[0;36mget_pyaudio\u001b[1;34m()\u001b[0m\n\u001b[0;32m    108\u001b[0m             \u001b[1;32mimport\u001b[0m \u001b[0mpyaudio\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    109\u001b[0m         \u001b[1;32mexcept\u001b[0m \u001b[0mImportError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 110\u001b[1;33m             \u001b[1;32mraise\u001b[0m \u001b[0mAttributeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Could not find PyAudio; check installation\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    111\u001b[0m         \u001b[1;32mfrom\u001b[0m \u001b[0mdistutils\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mversion\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mLooseVersion\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    112\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0mLooseVersion\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mpyaudio\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__version__\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m<\u001b[0m \u001b[0mLooseVersion\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"0.2.11\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mAttributeError\u001b[0m: Could not find PyAudio; check installation"
     ]
    }
   ],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b90b211",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3f826e6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9dc6360",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好\":\"请问有事吗？\",\n",
    "    \"你叫什么名字\":\"我是王嘉杰\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c19b8199",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa.get('你好')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "472a5bc7",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 3.3 实践"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a9401ab3",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "Could not find PyAudio; check installation",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32mD:\\pra\\Anaconda3\\lib\\site-packages\\speech_recognition\\__init__.py\u001b[0m in \u001b[0;36mget_pyaudio\u001b[1;34m()\u001b[0m\n\u001b[0;32m    107\u001b[0m         \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 108\u001b[1;33m             \u001b[1;32mimport\u001b[0m \u001b[0mpyaudio\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    109\u001b[0m         \u001b[1;32mexcept\u001b[0m \u001b[0mImportError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'pyaudio'",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-9-b1a71d1e75f9>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mspeech_recognition\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mRecognizer\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[1;32mwith\u001b[0m \u001b[0mspeech_recognition\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mMicrophone\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0msource\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      6\u001b[0m     \u001b[0maudio\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mr\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlisten\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0msource\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      7\u001b[0m \u001b[1;31m# 将数据保存到wav文件中\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\pra\\Anaconda3\\lib\\site-packages\\speech_recognition\\__init__.py\u001b[0m in \u001b[0;36m__init__\u001b[1;34m(self, device_index, sample_rate, chunk_size)\u001b[0m\n\u001b[0;32m     77\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     78\u001b[0m         \u001b[1;31m# set up PyAudio\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 79\u001b[1;33m         \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpyaudio_module\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_pyaudio\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     80\u001b[0m         \u001b[0maudio\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpyaudio_module\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mPyAudio\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     81\u001b[0m         \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\pra\\Anaconda3\\lib\\site-packages\\speech_recognition\\__init__.py\u001b[0m in \u001b[0;36mget_pyaudio\u001b[1;34m()\u001b[0m\n\u001b[0;32m    108\u001b[0m             \u001b[1;32mimport\u001b[0m \u001b[0mpyaudio\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    109\u001b[0m         \u001b[1;32mexcept\u001b[0m \u001b[0mImportError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 110\u001b[1;33m             \u001b[1;32mraise\u001b[0m \u001b[0mAttributeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Could not find PyAudio; check installation\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    111\u001b[0m         \u001b[1;32mfrom\u001b[0m \u001b[0mdistutils\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mversion\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mLooseVersion\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    112\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0mLooseVersion\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mpyaudio\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__version__\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m<\u001b[0m \u001b[0mLooseVersion\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"0.2.11\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mAttributeError\u001b[0m: Could not find PyAudio; check installation"
     ]
    }
   ],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "\n",
    "# 2.调用百度asr\n",
    "huang_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "\n",
    "asr_result = eval(asr(huang_token,\"1.wav\"))['result']\n",
    "asr_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79cc06c8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
